package com.demo.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EnumValidator implements ConstraintValidator<EnumValid, Object> {
    private Class<? extends Enum<?>> enumClass;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        enumClass = constraintAnnotation.enumClass();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        if (enumClass == null) {
            return false;
        }

        // 检查是否是有效的枚举值
        for (Enum<?> enumConstant : enumClass.getEnumConstants()) {
            if (enumConstant.name().equals(value.toString()) ||
                    (enumConstant instanceof BaseEnum &&
                            ((BaseEnum) enumConstant).getCode().equals(value))) {
                return true;
            }
        }
        return false;
    }
}